package com.rc.activity;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.rc.activity.dao.tbl_Count;
import com.rc.activity.dao.tbl_Item;
import com.rc.activity.dao.tbl_ItemDao;
import com.rc.activity.dao.tbl_Receipt;
import com.rc.activity.dao.tbl_Trip;
import com.rc.activity.dao.tbl_TripItems;
import com.rc.activity.provider.Contract;
import com.rc.adapter.AddExpenseAdpter;
import com.rc.adapter.DialogAdapter;
import com.rc.custom.MyListView;
import com.rc.db.DatabaseSupport;
import com.rc.object.ReceiptObj;
import com.rc.util.Util;
import com.telpoo.frame.ui.BaseActivity;

public class AddExpenseToTrip extends BaseActivity implements OnClickListener,
		OnCheckedChangeListener, TextWatcher {

	/**
	 * call Intent activity addExpense
	 */

	public static void callIntent(Activity at, long mTripID) {
		Intent it = new Intent(at, AddExpenseToTrip.class);
		it.putExtra("TRIP_ID", mTripID);
		at.startActivity(it);
	}

	// UI
	private MyListView lvExpense;
	private TextView txtFilterDate, txtFilterType, txtTitleContent, txtSearch;
	private RelativeLayout rlAllReceipt, rlFilterTime;
	private LinearLayout llCancel, llButtonContent, llSearch, llAddNew,
			llContent;
	private ImageView imgSearch;
	private ProgressBar pbLoad;

	private long mCategory = 0;
	private long mTripID = 0;
	private ArrayList<tbl_Item> arrItem = null;
	private ArrayList<ReceiptObj> arrReceiptObj;
	private ArrayList<tbl_Receipt> arrObjReceipt;
	private int mReceiptType = 0;
	private long start = 0;
	private long end = 0;
	private int numberFilter = 21;
	private Dialog dialog;
	private AddExpenseAdpter adpExpense;
	private ArrayList<HashMap<Long, ArrayList<tbl_Item>>> arrHmitem;
	private HashMap<Long, ArrayList<tbl_Item>> hmitem;
	private String mCategirize;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.trip_add_expense);

		arrHmitem = new ArrayList<HashMap<Long, ArrayList<tbl_Item>>>();
		hmitem = new HashMap<Long, ArrayList<tbl_Item>>();

		lvExpense = (MyListView) findViewById(R.id.lvExpense);
		txtFilterDate = (TextView) findViewById(R.id.txtFilterDate);
		txtFilterType = (TextView) findViewById(R.id.txtFilterType);
		txtTitleContent = (TextView) findViewById(R.id.txtTitleContent);
		llButtonContent = (LinearLayout) findViewById(R.id.llButtonContent);
		rlAllReceipt = (RelativeLayout) findViewById(R.id.rlAllReceipt);
		txtSearch = (TextView) findViewById(R.id.txtSearch);
		rlFilterTime = (RelativeLayout) findViewById(R.id.rlFilterTime);
		llCancel = (LinearLayout) findViewById(R.id.llCancel);
		llSearch = (LinearLayout) findViewById(R.id.llSearch);
		llAddNew = (LinearLayout) findViewById(R.id.llAddNew);
		llContent = (LinearLayout) findViewById(R.id.llContent);
		imgSearch = (ImageView) findViewById(R.id.imgSearch);
		pbLoad = (ProgressBar) findViewById(R.id.pbLoad);

		llSearch.setOnClickListener(this);
		llCancel.setOnClickListener(this);
		llAddNew.setOnClickListener(this);
		rlAllReceipt.setOnClickListener(this);
		rlFilterTime.setOnClickListener(this);

		addDateFilter();

		// call load data
		disableLayoutContent(false);
		new loadData().execute("");

		txtFilterDate.setText(getString(R.string.one_month));
		txtTitleContent.setText(getString(R.string.all_receipts));
		txtSearch.addTextChangedListener(this);
		if (getIntent() != null) {
			mTripID = getIntent().getLongExtra("TRIP_ID", 0);
		}
	}

	/**
	 * get receipt by filter 
	 */

	private void createDialogFilterReceipt() {
		dialog = new Dialog(AddExpenseToTrip.this);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_receipt_choosetime);
		final ListView lvDialog = (ListView) dialog.findViewById(R.id.lvDialog);
		DialogAdapter adpDialog = new DialogAdapter(AddExpenseToTrip.this,
				DatabaseSupport.getArrReceiptTypes(getResources(),
						AddExpenseToTrip.this), txtFilterType.getText()
						.toString());
		lvDialog.setAdapter(adpDialog);
		lvDialog.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				dialog.dismiss();
				String receiptType = ((TextView) lvDialog.getChildAt(position)
						.findViewById(R.id.txtTextDialog)).getText().toString();
				txtFilterType.setText(receiptType);
				txtTitleContent.setText(receiptType);
				mReceiptType = Util.getReceiptTypeByText(AddExpenseToTrip.this,
						receiptType);
				resetDataListView();
			}
		});
		dialog.show();
	}

	/**
	 *  get receipt by time
	 */
	private void createDialogFilterTime() {
		dialog = new Dialog(this);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_receipt_choosetime);
		final ListView lvDialog = (ListView) dialog.findViewById(R.id.lvDialog);
		ArrayList<tbl_Count> arrCount = new ArrayList<tbl_Count>();
		String[] lTime = getResources().getStringArray(R.array.filter_time);
		for (String item : lTime) {
			tbl_Count objCount = new tbl_Count();
			objCount.setName(item);
			objCount.setTotal("");
			arrCount.add(objCount);
		}
		DialogAdapter adpDialog = new DialogAdapter(this, arrCount,
				txtFilterDate.getText().toString());
		lvDialog.setAdapter(adpDialog);
		lvDialog.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				dialog.dismiss();
				txtFilterDate
						.setText(((TextView) lvDialog.getChildAt(position)
								.findViewById(R.id.txtTextDialog)).getText()
								.toString());
				int number = 0;
				switch (position) {
				case 0:
					number = 7;
					txtFilterDate.setText(getString(R.string.one_week));
					break;
				case 1:
					number = 14;
					txtFilterDate.setText(getString(R.string.two_weeks));
					break;
				case 2:
					number = 30;
					txtFilterDate.setText(getString(R.string.one_month));
					break;
				case 3:
					number = 90;
					txtFilterDate.setText(getString(R.string.three_months));
					break;
				case 4:
					number = 0;
					txtFilterDate.setText(getString(R.string.all_date));
				default:
					break;
				}
				numberFilter = number;
				addDateFilter();
				resetDataListView();
			}
		});
		((TextView) dialog.findViewById(R.id.txtTitle))
				.setText(getString(R.string.filter_receipts_by_time));
		dialog.show();
	}

	/**
	 * Noti data listview
	 */

	private void resetDataListView() {
		disableLayoutContent(false);
		new loadData().execute("");
	}

	@SuppressLint("SimpleDateFormat")
	private void addDateFilter() {
		if (numberFilter == 0) {
			end = 0;
			start = 0;
		} else {
			Calendar cal = Calendar.getInstance();
			SimpleDateFormat formatdate = new SimpleDateFormat("dd-MM-yyyy");
			String datenow = "";
			datenow = formatdate.format(cal.getTime());
			end = Util.parseDateForInt(datenow);
			String datefrom = Util.removeDateTime(numberFilter, "MM-dd-yyyy");
			datefrom = Util.formateDateFromstring("MM-dd-yyyy", "dd-MM-yyyy",
					datefrom);
			start = Util.parseDateForInt(datefrom);
		}

		if (numberFilter == 0) {
			start = 0;
			end = 0;
			return;
		}
		Timestamp timestamp = new Timestamp(Calendar.getInstance().getTime()
				.getTime());
		end = timestamp.getTime();
		start = Util.removeDateTime(numberFilter);

	}

	@Override
	protected void onResume() {
		super.onResume();
		disableLayoutContent(false);
	}

	/**
	 * áº©n hiá»‡n button content
	 */
	private void disableButtonContent(boolean isShow) {
		// if is show true Visible llButtonContent and disable txtSearch
		int showInt = isShow ? View.VISIBLE : View.GONE;
		llButtonContent.setVisibility(showInt);
		showInt = isShow ? View.GONE : View.VISIBLE;
		txtSearch.setVisibility(showInt);
		showInt = isShow ? R.drawable.ic_bar_search : R.drawable.ic_bar_cancel;
		imgSearch.setImageResource(showInt);
	}

	/**
	 * search listview
	 */
	public ArrayList<ReceiptObj> searchListView(
			ArrayList<ReceiptObj> arrReceipt, String contentSearch) {
		ArrayList<ReceiptObj> mArrTripList = new ArrayList<ReceiptObj>();
		for (int i = 0; i < arrReceipt.size(); i++) {
			String mMerchantName = arrReceipt.get(i).getMerchantName();
			if (mMerchantName != null) {
				if (mMerchantName.toUpperCase().contains(
						contentSearch.toUpperCase())) {
					mArrTripList.add(arrReceipt.get(i));
				}
			}

		}
		return mArrTripList;
	}

	private boolean isShow = false;

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.rlAllReceipt:
			createDialogFilterReceipt();
			break;
		case R.id.rlFilterTime:
			createDialogFilterTime();
			break;
		case R.id.llCancel:
			finish();
			break;
		case R.id.llSearch:
			disableButtonContent(isShow);
			isShow = isShow ? false : true;
			Util.HidenKeyBoard(AddExpenseToTrip.this);
			break;
		case R.id.llAddNew:
			CategorizeItems.callIntent(AddExpenseToTrip.this);
			break;
		default:
			break;
		}
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		if (txtSearch.getText().toString().length() > 0) {
			// TODO
		} else {
			resetDataListView();
		}
	}

	@Override
	public void afterTextChanged(Editable s) {

	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		switch (buttonView.getId()) {
		case R.id.cbMulti:
			tbl_Item objItem = (tbl_Item) buttonView.getTag();
			if (isChecked) {
				arrItem.add(objItem);
			} else {
				arrItem.remove(objItem);
			}
			break;

		default:
			break;
		}

	}

	private int updateItem() {
		int row = 0;
		for (tbl_Item objItem : arrItem) {
			if (objItem.isCheck()) {

				if (mCategory != 0) {
					objItem.setCategoryID(mCategory);
				}
				objItem.setTripID(mTripID);
				objItem.setIsUpdate("1");
				row = this.getContentResolver().update(
						Contract.CONTENT_URI_ITEMS,
						objItem.getContentValues(),
						tbl_ItemDao.Properties.ItemID.columnName + " = "
								+ objItem.getItemID(), null);
				tbl_TripItems objTripItem = new tbl_TripItems();
				float approved = 0;
				objTripItem.setApproved(approved);
				objTripItem.setTripID(mTripID + "");
				objTripItem.setTripItemID(objItem.getItemID());
				objTripItem.setIsApproved(0);
				objTripItem.setIsClaimed(1);
				objTripItem.setClaimed(Util.convertFloat(objItem.getAmount()));
				objTripItem.setIsCreate("1");
				objTripItem.setIsDelete("");
				this.getContentResolver().insert(
						Contract.CONTENT_URI_TRIP_ITEM,
						objTripItem.getContentValues());
			}
		}

		if (row > 0) {
			tbl_Trip objTrip = new tbl_Trip();
			objTrip = DatabaseSupport.getTripByID(mTripID,
					AddExpenseToTrip.this);
			if (!"false".equals(objTrip.getCategories())) {
				mCategirize = objTrip.getCategories() == null ? mCategirize
						: (objTrip.getCategories().indexOf(mCategirize + "") == -1 ? objTrip
								.getCategories() + "," + mCategirize
								: objTrip.getCategories());
			}
		}

		return row;
	}

	/**
	 * disable layout content and visable progressbar
	 */
	private void disableLayoutContent(boolean isShow) {
		if (isShow) {
			pbLoad.setVisibility(View.GONE);
			llContent.setVisibility(View.VISIBLE);
		} else {
			pbLoad.setVisibility(View.VISIBLE);
			llContent.setVisibility(View.GONE);
		}
	}

	private class loadData extends AsyncTask<String, Void, Bitmap> {

		protected Bitmap doInBackground(String... urls) {
			// arr ReceiptObj
			arrReceiptObj = new ArrayList<ReceiptObj>();

			// arr item
			arrItem = new ArrayList<tbl_Item>();

			// arr tbl_Receipt
			arrObjReceipt = new ArrayList<tbl_Receipt>();

			// add data tbl_Receipt
			arrObjReceipt = DatabaseSupport.getReceiptAddExpense(0,
					mReceiptType, start, end, AddExpenseToTrip.this);
			for (int i = 0; i < arrObjReceipt.size(); i++) {

				// clear data arr Item
				arrItem = new ArrayList<tbl_Item>();
				arrItem.clear();
				arrItem = DatabaseSupport.getItemsByReceiptIDNonReport(
						arrObjReceipt.get(i).getReceiptID(),
						AddExpenseToTrip.this);

				if (arrItem.size() > 0) {
					tbl_Receipt objtbl_Receipt = new tbl_Receipt();
					objtbl_Receipt = arrObjReceipt.get(i);
					// add receipt
					arrReceiptObj.add(DatabaseSupport.convertReceiptObj(
							objtbl_Receipt, AddExpenseToTrip.this));
					hmitem.put(objtbl_Receipt.getReceiptID(), arrItem);
					arrHmitem.add(hmitem);
				}

			}
			return null;
		}

		protected void onPostExecute(Bitmap result) {
			if (adpExpense != null) {
				adpExpense.NotiDB(arrReceiptObj, arrHmitem);
			} else {
				adpExpense = new AddExpenseAdpter(AddExpenseToTrip.this,
						arrReceiptObj, arrHmitem, AddExpenseToTrip.this);
				lvExpense.setAdapter(adpExpense);
			}
			disableLayoutContent(true);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (data.getExtras().containsKey("CATEGORY_ID")) {
			disableLayoutContent(false);
			disableButtonContent(false);
			mCategory = data.getLongExtra("CATEGORY_ID", 0);
			mCategirize = mCategory + "";
			new addItemToTrip().execute("");

		}

	}

	private class addItemToTrip extends AsyncTask<String, Void, Integer> {

		protected Integer doInBackground(String... urls) {
			if (updateItem() > 0) {
				return DatabaseSupport.updateAmountCategorizeTripByID(mTripID,
						mCategirize, AddExpenseToTrip.this);
			}
			return 0;
		}

		protected void onPostExecute(Integer result) {
			finish();
		}
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		finish();
	}

}
